//
//  main.m
//  RuntimTest
//
//  Created by wangrui on 13-10-17.
//  Copyright (c) 2013年 PPS. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "TestSubObject.h"

#import <objc/objc.h>
#import <objc/runtime.h>
#import <objc/message.h>

BOOL create_class(const char *new_cls_name,const char *super_cls_name){
    /**
     * objc_class * 被禁用了. 只能用Class
     */
    Class meta_cls;
    Class super_cls;
    Class root_cls;
    Class new_cls;
    
    //确保是有父类的
    super_cls = objc_lookUpClass(super_cls_name);
    if (!super_cls) {
        return NO;
    }
    
    //创建的新类已经存在
    if (objc_lookUpClass(new_cls_name)) {
        return YES;
    }
    
    /**
     * 现在只能用class_getSuperclass获取父类，原来可以用 root_cls->superClass
     * 新的class 用的是class_t. 具体的联系还有待研究
     */
    
    //找到根类
    root_cls = super_cls;
    while (class_getSuperclass(root_cls)) {
        root_cls = class_getSuperclass(root_cls);
    }
    
    //objc_addClass() 已不能使用, 写不下去了
    
    return YES;
}


void ReportFunction(id self,SEL s){
//    NSLog(@"%@",NSStringFromSelector(s));
//    printf("test\n");
    
    NSLog(@" >> This object is %p.", self);
    NSLog(@" >> Class is %@, and super is %@.", [self class], [self superclass]);
    
    Class prevClass = NULL;
    int count = 1;
    for (Class currentClass = [self class]; currentClass; ++count) {
        prevClass = currentClass;
        NSLog(@" >> Following the isa pointer %d times gives %p", count, currentClass);
        currentClass = object_getClass(currentClass);
        
        if (prevClass == currentClass)
            break;
    }
    
    NSLog(@" >> NSObject's class is %p", [NSObject class]);
    NSLog(@" >> NSObject's meta class is %p", object_getClass([NSObject class]));
}


int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        Class new_class = objc_allocateClassPair([NSString class], "NSStringSub", 0);
        
        SEL s = sel_getUid("nsstringSubCall");
        class_addMethod(new_class,s, (IMP)ReportFunction,"v@:");
        objc_registerClassPair(new_class);
        
        id c = [[new_class alloc]init];
        [c performSelector:s];
        
    }
    
    return 0;
}

